<template>
  <!-- 新增、修改改目标标准 -->
  <el-dialog :title="addParams.title" :visible.sync="addParams.visible" :close-on-click-modal="false" width="800px">
    <el-form :model="formData" :rules="rules" ref="ruleForm" label-width="130px" class="ruleForm">
      <el-form-item label="父级目标标准" prop="parentId" v-if="addParams.type === 'child'">
        <el-select v-model="formData.parentId" disabled placeholder="请选择复制对象">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in parentData" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="复制对象" required v-if="addParams.type === 'copy'">
        <el-select v-model="formData.sourceId" filterable placeholder="请选择复制对象">
          <el-option :label="item.name" :value="item.id" v-for="(item, index) in parentData" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="目标标准名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="所属诊改阶段" prop="year">
        <el-select v-model="formData.year" placeholder="请选择所属诊改阶段">
          <el-option v-for="year in yearArr" :key="year" :label="year" :value="year"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="责任部门" prop="dutyPart" required>
        <el-select v-model="formData.dutyPart" filterable placeholder="请选择责任部门" @change="changeDept">
          <el-option :label="item.orgName" :value="item.id" v-for="item in organizeArr" :key="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="dutyUser">
        <el-select v-model="formData.dutyUser" filterable placeholder="请选择负责人" disabled>
          <el-option :label="item.realName" :value="item.id" v-for="(item,index) in deptUserArr" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="管理员" prop="adminId">
        <el-select v-model="formData.adminId" filterable placeholder="请选择管理员" disabled>
          <el-option :label="item.realName" :value="item.id" v-for="(item,index) in deptUserArr" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="适用范围" prop="rectificationRangeId">
        <el-cascader @change="changeRange" v-model="formData.rectificationRangeId" :options="rectificationRange" filterable :show-all-levels="false" :props="{label: 'name',value: 'id'}">
        </el-cascader>
      </el-form-item>
      <!--<el-form-item label="诊改对象" class="response" prop="rectificationObject">-->
      <!--<el-input type="textarea" disabled v-model="formData.rectificationObject"></el-input>-->
      <!--</el-form-item>-->
      <!-- 后台不存，仅做展示 -->
      <template v-if="rangeChildList.length > 1">
        <el-form-item v-for="(item,index) in rangeChildList" :key="index" :label="`诊改对象-${item.name}`" class="response">
          <el-input type="textarea" disabled v-model="item.rectificationObjectStr"></el-input>
        </el-form-item>
      </template>
      <el-form-item v-else label="诊改对象" class="response" prop="rectificationObjectStr">
        <el-input type="textarea" disabled v-model="formData.rectificationObjectStr"></el-input>
      </el-form-item>

      <el-form-item label="本部门参与人" prop="joinUsers" class="response">
        <el-select v-model="formData.joinUsers" filterable multiple placeholder="请选择本部门参与人">
          <el-option :label="item.realName" :value="item.id" v-for="(item,index) in deptUserArr" :key="index" :disabled="formData.dutyUser == item.id || formData.adminId == item.id || formData.shareUsers.indexOf(item.id)>-1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="参与部门" prop="joinOrgs" class="response">
        <el-select v-model="formData.joinOrgs" filterable multiple placeholder="请选择参与部门">
          <el-option :label="item.orgName" :value="item.id" v-for="(item, index) in organizeArr" :key="index" :disabled="formData.dutyPart == item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="共享人" prop="shareUsers" class="response">
        <el-col style="width: 48%">
          <el-select v-model="tempOrg" filterable placeholder="请先选择共享人部门" @change="changeDept(tempOrg, true)">
            <el-option :label="item.orgName" :value="item.id" v-for="item in organizeArr" :key="item.id"></el-option>
          </el-select>
        </el-col>
        <el-col style="margin-left: 4%; width: 48%">
          <el-select v-model="formData.shareUsers" :disabled="formData.examineState>0" multiple filterable placeholder="请选择共享人" @change="$forceUpdate()">
            <el-option :label="item.realName" :value="item.id" v-for="(item,index) in shareUserDataArr" :key="index">
              {{ item.realName }}
              <!-- <p style="float: right; color: #8492a6; font-size: 13px;padding-right: 15px">所属部门：{{ item.orgName || '无' }}</p> -->
            </el-option>
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="备注" prop="desc" class="response">
        <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 8}" v-model="formData.desc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addParams.visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getStorage } from '@/config/utils'
import { addFormWorkData, copyFormWorkData, addSubTarget } from '@/api/target'
import { getStrByRangeId } from '@/api/system'
import { getAllOrganize, getUserByDept, getAdminAndChargeByOrgId } from '../../../../api/systemManage'

export default {
  name: 'addDialog',
  props: {
    addParams: {
      type: Object,
      default: false
    },
    levelType: {
      type: String
    },
    currentId: {
      type: [Number, String]
    },
    // 复制对象
    parentData: {
      type: Array
    }
  },
  data() {
    return {
      formData: {
        name: '',
        indexX: this.levelType,
        parentId: '',
        sourceId: '',
        rectificationRangeId: '',
        year: '',
        dutyPart: '',
        desc: '',
        rectificationObjectStr: '',
        dutyUser: '',
        adminId: '',
        joinUsers: [],
        joinOrgs: [],
        shareUsers: ''
      },
      yearArr: this.$config.yearArr(),
      rules: {
        name: [{ required: true, message: '请输入目标标准名称', trigger: 'blur' }],
        year: [{ required: true, message: '请选择年度', trigger: 'change' }],
        dutyPart: [{ required: true, message: '请选择责任部门', trigger: 'change' }],
        rectificationRangeId: [{ required: true, message: '请选择适用范围', trigger: 'change' }],
        rectificationObjectStr: [{ required: true, message: '诊改对象不能为空' }]
      },
      // 责任部门
      organizeArr: [],
      // 本部门参与人
      deptUserArr: [],
      // 共享人
      shareUserDataArr: [],
      tempOrg: null,
      // 适用范围
      rectificationRange: [],
      // 根据适用范围回显的诊改对象
      rectificationObject: [],
      // 适用范围（角度=也就是页面上tab值）
      // 所选适用范围下的三级数据
      rangeChildList: []
    }
  },
  computed: {
    // 适用范围
    rangeList() {
      const temp = getStorage('rangeList')
      temp.forEach(item => {
        item.id = 0
        item.subList = [...item.rectificationRangeDTOList]
      })
      return temp
    }
  },
  created() {
    this.getOrganize()
    // this.getAllUser();

    // this.getRectificationObject();
    if (this.addParams.type === 'copy') {
      // 复制，回显复制对象
      this.formData.sourceId = this.currentId
    } else if (this.addParams.type === 'child') {
      // 新增子项，回显父级目标标准
      this.formData.parentId = this.currentId
    }

    const temp = getStorage('rangeList')
    temp.forEach(item => {
      if (item.code === this.levelType) {
        this.rectificationRange = item.rectificationRangeDTOList
      }
    })
  },
  methods: {
    // 获取责任部门下拉数据
    getOrganize() {
      getAllOrganize()
        .then(res => {
          this.organizeArr = res || []
        })
        .catch()
    },
    // 获取所有用户
    // getAllUser() {
    //     getAllUser().then(res => {
    //         this.userDataArr = res || []
    //     }).catch(() => {})
    // },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = null
          switch (this.addParams.type) {
            case 'add':
              params = this.formData
              const len = params.rectificationRangeId.length - 1
              params.rectificationRangeId = params.rectificationRangeId[len]
              params.state = '0'
              delete this.formData.parentId
              addFormWorkData(params)
                .then(res => {
                  if (res) {
                    this.$message.success('操作成功')
                    this.$emit('getList')
                    this.addParams.visible = false
                  }
                })
                .catch()
              break
            case 'copy':
              params = this.formData
              const i = params.rectificationRangeId.length - 1
              params.rectificationRangeId = params.rectificationRangeId[i]
              copyFormWorkData(params)
                .then(res => {
                  if (res) {
                    this.$message.success('操作成功')
                    this.$emit('getList')
                    this.addParams.visible = false
                  }
                })
                .catch()
              break
            case 'child':
              params = this.formData
              const j = params.rectificationRangeId.length - 1
              params.rectificationRangeId = params.rectificationRangeId[j]
              addSubTarget(params)
                .then(res => {
                  if (res) {
                    this.$message.success('操作成功')
                    this.$emit('getList')
                    this.addParams.visible = false
                  }
                })
                .catch()
              break
          }
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    // 递归处理数据
    recursiveRangeList(item) {
      if (item.hasOwnProperty('subList') && item.subList) {
        item.children = [...item.subList]
        this.recursiveRangeList(item.subList)
        return item
      }
    },
    // 根据选中的适用范围回显诊改对象
    changeRange(val) {
      // console.log(val, this.rectificationRange);
      const temp = this.rectificationRange.filter(item => {
        if (item.id === val[0]) {
          return item.subList
        }
      })
      // console.log(temp);
      if (temp.length && temp[0].subList) {
        this.rangeChildList = temp[0].subList
        this.rangeChildList.forEach((item, index) => {
          this.getRangeList(item.id, index)
          // console.log('诊改对象', item.id , this.rangeChildList);
        })
      } else {
        this.rangeChildList = []
        getStrByRangeId({ rangeId: val[0] }).then(res => {
          this.$set(this.formData, 'rectificationObjectStr', res)
        })
      }
    },
    getRangeList(rangeId, index) {
      getStrByRangeId({ rangeId: rangeId }).then(res => {
        this.$set(this.rangeChildList[index], 'rectificationObjectStr', res)
      })
    },
    // 根据责任部门查询部门人员
    changeDept(val, isShareDept) {
      this.formData.joinUsers = []
      getUserByDept(val)
        .then(res => {
          if (isShareDept) {
            this.shareUserDataArr = new Set([...this.shareUserDataArr, ...res])
          } else {
            this.deptUserArr = res || []
          }
        })
        .catch(() => {})
      if (!isShareDept) {
        getAdminAndChargeByOrgId(val)
          .then(res => {
            if (res) {
              this.$set(this.formData, 'dutyUser', res.chargePerson)
              this.$set(this.formData, 'adminId', res.adminPerson)
            }
          })
          .catch(() => {})
      }
    }
  },
  beforeDestroy() {
    this.resetForm()
  }
}
</script>

<style lang="scss" scoped>
.ruleForm {
  display: flex;
  flex-wrap: wrap;
  .el-form-item {
    width: 50%;
  }
  .el-cascader {
    width: 100% !important;
  }
}
</style>
